<template>
  <div class="add-account">
    <el-card>
      <template #header>
        <h3>开户</h3>
      </template>

      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          label-position="top"
      >
        <el-form-item label="客户ID" prop="customerId">
          <el-input-number v-model="form.customerId" :min="1" />
        </el-form-item>

        <el-form-item label="账户类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="SAVING">储蓄账户</el-radio>
            <el-radio label="CHECKING">支票账户</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { accountApi } from '../../api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const formRef = ref(null)

const form = ref({
  customerId: null,
  type: 'SAVING'
})

const rules = {
  customerId: [
    { required: true, message: '请选择客户', trigger: 'blur' },
    { type: 'number', min: 1, message: '客户ID必须大于0', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择账户类型', trigger: 'change' }
  ]
}

const submitForm = async () => {
  try {
    await formRef.value.validate()
    const response = await accountApi.addAccount(form.value)
    ElMessage.success('开户成功')
    router.push('/accounts')
  } catch (error) {
    ElMessage.error('开户失败')
  }
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<style scoped>
.add-account {
  max-width: 600px;
  margin: 0 auto;
}
</style>